<?php

namespace App\Api\Dao;

use App\Exceptions\DaoException;
use App\Helpers\Lib\RedisService;
use App\Helpers\Lib\WechatPay;
use App\Helpers\ResponseEnum;
use App\Models\TongGood;
use App\Models\TongGoodsGroup;
use App\Models\TongOrder;
use App\Models\TongUser;
use App\Models\TongUserAddress;
use App\Models\TongUserProfit;
use App\Models\TongUserProfitTest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderDao extends BaseDao
{
    /**
     * 清空未支付的订单
     * @return void
     */
    public static function CancleOrder()
    {
        TongOrder::query()->where('status',0)->where('created_at', '<=', now()->subMinutes(15))->chunk(1,function($flow){
            foreach ($flow as $item){
                $order_id = $item['id'];
                Log::info('清除订单'.$order_id);
                //将流水的记录修改成为已到账
                TongOrder::query()->where('id',$order_id)->where('status',0)->delete();
            }
        });
    }

    /**
     * 查询构造器
     * @param $data
     * @return \Illuminate\Database\Eloquent\Builder
     */
    function getBuildQuery($data)
    {
        // TODO: Implement getBuildQuery() method.
        $query = TongOrder::query();
        if(checkIsHasField($data,'id')){
            $query->where('id',$data['id']);
        }
        if(checkIsHasField($data,'u_id')){
            $query->where('u_id',$data['u_id']);
        }
        if(checkIsHasField($data,'status')){
            $query->where('status',$data['status']);
        }
        $query->orderBy('created_at','desc');
        return $query;
    }

    /**
     * 添加订单
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|void
     */
    public function addOrder(array $params)
    {
        //获取商品详情
        $goodsInfo = (new GoodsDao())->getBuildQuery(['id'=>$params['goods_id']])->first()->toArray();
        //获取用户详情
        $userInfo = (new UserDao())->getBuildQuery(['id'=>$params['u_id']])->first()->toArray();
        if($userInfo['identity_id']==1){
            //如果购买的是3980
            $params['order_price'] = bcmul($goodsInfo['experience_member_price'],$params['goods_num'],2);
            $params['all_order_price'] = bcmul($goodsInfo['experience_member_price'],$params['goods_num'],2);
        }elseif($userInfo['identity_id']==2){
            //品牌会员
            $params['order_price'] = bcmul($goodsInfo['brand_member_price'],$params['goods_num'],2);
            $params['all_order_price'] = bcmul($goodsInfo['brand_member_price'],$params['goods_num'],2);
        }elseif ($userInfo['identity_id']==3){
            //店铺
            $params['order_price'] = bcmul($goodsInfo['store_price'],$params['goods_num'],2);
            $params['all_order_price'] = bcmul($goodsInfo['store_price'],$params['goods_num'],2);
        }elseif ($userInfo['identity_id']==4){
            //分公司
            $params['order_price'] = bcmul($goodsInfo['company_price'],$params['goods_num'],2);
            $params['all_order_price'] = bcmul($goodsInfo['company_price'],$params['goods_num'],2);
        }elseif ($userInfo['identity_id']==5){
            //区县代理
            $params['order_price'] = bcmul($goodsInfo['area_price'],$params['goods_num'],2);
            $params['all_order_price'] = bcmul($goodsInfo['area_price'],$params['goods_num'],2);

        }elseif ($userInfo['identity_id']==6){
            $params['order_price'] = bcmul($goodsInfo['city_price'],$params['goods_num'],2);
            $params['all_order_price'] = bcmul($goodsInfo['city_price'],$params['goods_num'],2);
        }elseif($userInfo['identity_id']==7){
            //合伙人
            $params['order_price'] = bcmul($goodsInfo['partner_price'],$params['goods_num'],2);
            $params['all_order_price'] = bcmul($goodsInfo['partner_price'],$params['goods_num'],2);
        }else{
            $params['order_price'] = bcmul($goodsInfo['price'],$params['goods_num'],2);
            $params['all_order_price'] = bcmul($goodsInfo['price'],$params['goods_num'],2);
        }

        //获取地址详情
        $addressInfo = (new UserAddressDao())->getBuildQuery(['id'=>$params['address_id'],'u_id'=>$params['u_id']])->first()->toArray();
        $params['order_no'] = makeOrderNo();
        $params['order_goods_info'] = json_encode($goodsInfo);
//        $params['order_price'] = bcmul($goodsInfo['price'],$params['goods_num'],2);
//        $params['all_order_price'] = bcmul($goodsInfo['price'],$params['goods_num'],2);
        $params['order_address_info'] = json_encode($addressInfo);
        $params['goods_price'] = $goodsInfo['price'];
        if(config("test.test_start")==1 && in_array($params['u_id'],explode(',',str_replace('，', ',', config("test.test_user"))))){
            $params['is_test'] = 1;
        }
        $result = TongOrder::query()->create($params);
        if(!$result){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'创建订单失败');
        }
        return $result;
    }

    /**
     * 用户钱包支付
     * @param array $params
     * @return true
     */
    public function payNotice(array $params)
    {
        $TongOrderModel = TongOrder::query();
        $TongUserModel = TongUser::query();
        $TongUserProfitModel = TongUserProfit::query();
        //获取订单详情
        $order_info = $TongOrderModel->where('id',$params['id'])
            ->where('u_id',$params['u_id'])->first();
        //获取用户信息
        $user_info = $TongUserModel->where('id',$params['u_id'])->first();
        if(!config("test.test_start")==1 && !in_array($user_info['id'],explode(',',str_replace('，', ',', config("test.test_user"))))) {
            if ($user_info['money'] < $order_info['order_price']) {
                throw new DaoException(ResponseEnum::HTTP_ERROR, '钱包余额不足');
            }
        }
        $old_identity_id = $user_info['identity_id'];
        DB::beginTransaction();
        try {
            //修改订单状态
            $TongOrderModel->where('id',$params['id'])->update(['status'=>1,'pay_status'=>0,'pay_time'=>date('Y-m-d h:i:s',time())]);
            if(config("test.test_start")==1 && in_array($user_info['id'],explode(',',str_replace('，', ',', config("test.test_user"))))){
                TongUserProfitTest::query()->create([
                    'u_id'=>$user_info['id'],
                    'order_id'=>$order_info['id'],
                    'money'=>-$order_info['order_price'],
                    'type'=>1, //订单
                    'symbol'=>2, //支出
                    'status'=>1,//已到账
                    'remark'=>'购买商品扣除'
                ]);
            }else{
                //扣除用户余额
                $TongUserModel->where('id',$params['u_id'])->decrement('money',$order_info['order_price']);
                //记录流水
                $TongUserProfitModel->create([
                    'u_id'=>$user_info['id'],
                    'order_id'=>$order_info['id'],
                    'money'=>-$order_info['order_price'],
                    'type'=>1, //订单
                    'symbol'=>2, //支出
                    'status'=>1,//已到账
                    'remark'=>'购买商品扣除',
                    'befor_money'=>$user_info['money'],
                    'after_money'=>bcsub($user_info['money'],$order_info['order_price'],2),
                ]);
            }

            //用户的业绩统计
            if(!config("test.test_start")==1 && !in_array($user_info['id'],explode(',',str_replace('，', ',', config("test.test_user"))))){
                //如果不开启测试才进行业绩统计
                user_statistics_order($user_info['id'],$order_info['order_price']);
            }


            //只有会员商品才会参与反润
            if($order_info['order_type']==1 && ($order_info['order_goods_info']!==null && $order_info['order_goods_info']['is_shop_goods']==0)){
//                if(isSmallToBig($order_info['id'])){
//                    price_difference_upgrade_tow($user_info['id'],$order_info['id']);
//                }else{
//                    //自己购买商品补差价升级
//                    price_difference_upgrade($user_info['id'],$order_info['id']);
//                }
                //price_difference_upgrade($user_info['id'],$order_info['id']);
                price_difference_upgrade($user_info['id'],$order_info['id']);
                leaderReward($user_info['id'],$order_info['id']); //每个新单给领导奖励
                //调用自动升级（邀请团队业绩）
                //userUpgrade($user_info['id']);
                //商品的复购津贴
                $new_user_info = RedisService::hGet($user_info['id']);
                if($old_identity_id==$new_user_info['identity_id']){
                    new_user_fugou($user_info['id'],$order_info['id']);
                    leaderReward($user_info['id'],$order_info['id']); //每个新单给领导奖励
                    new_area_money($user_info['id'],$order_info['id']);

                }

                //公司的区域津贴
                //area_money($order_info['u_id'],$order_info['id']);
                new_area_money($user_info['id'],$order_info['id']);
            }elseif ($order_info['order_goods_info']['is_shop_goods']==2){
                //会员专享的商品
                //商品的复购津贴
                //repurchase_money($order_info['id']);
                new_user_fugou($user_info['id'],$order_info['id']);
                leaderReward($user_info['id'],$order_info['id']); //每个新单给领导奖励
                new_area_money($user_info['id'],$order_info['id']);
            }

            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();
            throw new DaoException(ResponseEnum::DAO_ERROR,$e->getMessage());
        }
    }

    public function payRepeatMoneyNotice(array $params)
    {
        $TongOrderModel = TongOrder::query();
        $TongUserModel = TongUser::query();
        $TongUserProfitModel = TongUserProfit::query();
        //获取订单详情
        $order_info = $TongOrderModel->where('id',$params['id'])
            ->where('u_id',$params['u_id'])->first();
        //获取用户信息
        $user_info = $TongUserModel->where('id',$params['u_id'])->first();
//        if($order_info['order_type']==1){
//            ///$goods_json_data = json_decode($order_info['order_goods_info'],true);
//            $goods_price = $order_info['order_goods_info']['price'];
//        }else{
//            //$goods_json_data = json_decode($order_info['order_group_goods_info'],true);
//            $goods_price = $order_info['order_group_goods_info']['goods_group_price'];
//        }
        $temp_real_price = bcmul($order_info['goods_price'],$order_info['goods_num'],2);
        if($user_info['repeat_money']<$temp_real_price){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'复购券余额不足');
        }
        DB::beginTransaction();
        try {
            //修改订单状态 并且将订单修改成为原价
            $TongOrderModel->where('id',$params['id'])->update(['status'=>1,'pay_status'=>2,'pay_time'=>date('Y-m-d h:i:s',time()),'order_price'=>$temp_real_price,'all_order_price'=>$temp_real_price]);
            //扣除用户余额

            $TongUserModel->where('id',$params['u_id'])->decrement('repeat_money',$temp_real_price);
            //记录流水
            $TongUserProfitModel->create([
                'u_id'=>$user_info['id'],
                'order_id'=>$order_info['id'],
                'money'=>-$temp_real_price,
                'type'=>10, //订单
                'symbol'=>2, //支出
                'status'=>1,//已到账
                'remark'=>'复购券购买商品扣除'
            ]);

            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();
            throw new DaoException(ResponseEnum::DAO_ERROR,$e->getMessage());
        }
    }

    /**
     * 获取订单详请
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|void
     */
    public function getOrderInfo(array $params)
    {
        return self::getBuildQuery($params)->first();
    }

    /**
     * 获取订单列表
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getOrderList(array $params)
    {
        if(checkIsHasField($params,'status') && $params['status']==-1){
            unset($params['status']);
        }
        return $this->getBuildQuery($params)->paginate($params['pageSize']);
    }

    /**
     * 微信支付
     * @param array $params
     * @return array
     */
    public function wechatPay(array $params)
    {
        $TongOrderModel = TongOrder::query();
        $TongUserModel = TongUser::query();
        $TongUserProfitModel = TongUserProfit::query();
        //获取订单详情
        $order_info = $TongOrderModel->where('id',$params['id'])
            ->where('u_id',$params['u_id'])->first();
        //获取用户信息
        //var_dump($order_info['order_goods_info']['goods_name']);exit();
        $user_info = $TongUserModel->where('id',$params['u_id'])->first();
        if($order_info['order_type']==1){
            $pay_data= ['order_no'=>$order_info['order_no'],'description'=>$order_info['order_goods_info']['goods_name'],'openid'=>$user_info['openid'],'order_price'=>$order_info['all_order_price'],'pay_price'=>$order_info['order_price']];
            $pay_data['pay_price'] = bcsub($pay_data['pay_price'],randOrderMoney(),2);
        }else{
            $pay_data= ['order_no'=>$order_info['order_no'],'description'=>$order_info['order_group_goods_info']['goods_group_name'],'openid'=>$user_info['openid'],'order_price'=>$order_info['all_order_price'],'pay_price'=>$order_info['order_price']];
            $pay_data['pay_price'] = bcsub($pay_data['pay_price'],randOrderMoney(),2);
        }
        return (new WechatPay())->to_pay($pay_data);
    }

    /**
     * 创建套餐订单
     * @param array $params
     * @return void
     */
    public function addGroupOrder(array $params)
    {
        //获取商品的详情
        $group_goods_info = TongGoodsGroup::query()->where('id',$params['goods_group_id'])->with(['values'])->first()->toArray();
        $order_price = $group_goods_info['goods_group_price']* $params['goods_num'];
        //获取地址详情
        $addressInfo = (new UserAddressDao())->getBuildQuery(['id'=>$params['address_id'],'u_id'=>$params['u_id']])->first()->toArray();
        //计算订单的价格
        $insert_order_data = [
            'order_no'=>'G'.makeOrderNo(),
            'u_id'=>$params['u_id'],
            'group_goods_id'=>$group_goods_info['id'],
            'goods_num'=>$params['goods_num'],
            'goods_price'=>$group_goods_info['goods_group_price'],
            'order_price'=>$order_price,
            'all_order_price'=>$order_price,
            'order_group_goods_info'=>json_encode($group_goods_info),
            'order_address_info'=>json_encode($addressInfo),
            'address_id'=>$params['address_id'],
            'order_type'=>2,//套餐订单
            'v_id'=>$params['v_id'],//用户选择的是哪个套餐
        ];
        $result = TongOrder::query()->create($insert_order_data);
        if(!$result){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'创建订单失败');
        }
        return $result;
    }

    /**
     * 是否允许用户复购多单
     * @param array $params
     * @return bool
     * @throws DaoException
     */
    public function moreGoods(array $params)
    {
        $flag = false;
        //获取商品的详情
        $goods_query = TongGood::query()->where('id',$params['goods_id']);
        if(!$goods_query->exists()){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'商品不存在');
        }
        //获取用户的信息
        $userInfo = TongUser::query()->where('id',$params['u_id'])->first();

        $goods_info = $goods_query->first();

        if($goods_info['is_shop_goods']==1 or $goods_info['is_shop_goods']==2){
            $flag = true;
            return $flag;
        }else{
            if($userInfo['identity_id']==3 or $userInfo['identity_id']==4 or $userInfo['identity_id']==5){
                $flag = true;
                return $flag;
            }
            if($userInfo['identity_id']==2){
                if((int)$goods_info['price']==399 or (int)$goods_info['price']==3980){
                    $flag = true;
                    return $flag;
                }
            }
            if($userInfo['identity_id']==1){
                if((int)$goods_info['price']==399){
                    $flag = true;
                    return $flag;
                }
            }
        }
        return $flag;
    }

    /**
     * 获取好友的订单
     * @param array $data
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|void
     */
    public function getFriendUserOrder(array $data)
    {
        return $this->getBuildQuery(['u_id'=>$data['friend_id']])->whereIn('status',[1,3,4,5])->get();
    }

    /**
     * 重置用户的登录密码
     * @param array $data
     * @return int
     */
    public function resetUserPassword(array $data)
    {
        return TongUser::query()->where('mobile',$data['phone'])->update(['password'=>$data['new_password']]);
    }

    /**
     * 待发货订单修改地址
     * @param array $params
     * @return true
     */
    public function updateOrderAddress(array $params)
    {

        DB::transaction(function () use($params) {
            //获取订单的详情
            $order_info = TongOrder::query()->where('u_id',$params['u_id'])->where('id',$params['id'])->first();
            //查询用户的分配的区域奖励
            $area_money_query = TongUserProfit::query()->where('order_id',$order_info['id'])
                ->where('status',1)//查询已到账的
                ->orWhere('type',6)
                ->orWhere('type',14)
                ->where('symbol',1); //查询收入的
            if($area_money_query->exists()){
                //有区域奖励需要扣除奖励
                $area_money_arr = $area_money_query->get()->toArray();
                foreach ($area_money_arr as $key=>$value){
                    TongUser::query()->where('id',$value['u_id'])->decrement('money',$value['money']);
                    TongUserProfit::query()->create([
                        'u_id'=>$value['u_id'],
                        'order_id'=>$value['order_id'],
                        'type'=>$value['type'],
                        'money'=>$value['money'],
                        'symbol'=>2,
                        'status'=>1,
                        'remark'=>'用户修改订单区域奖励扣除-'.$value['money']
                    ]);
                }
            }
            //获取地址的详情
            $user_address_info  = TongUserAddress::query()->where('u_id',$params['u_id'])->where('id',$params['address_id'])->first()->toArray();
            TongOrder::query()->where('id',$order_info['id'])->update([
                'order_address_info'=>json_encode($user_address_info)
            ]);
            //扣除完成后根据地址重新进行区域奖励的分发
            area_money($order_info['u_id'],$order_info['id']);
        });
        return true;




    }
}
